function resetScene() {
    fetch('/reset_scene', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({})
    })
    .then(response => response.json())
    .then(data => console.log('Success:', data))
    .catch((error) => console.error('Error:', error));
}
function filterVideos() {
    const checkedTags = Array.from(document.querySelectorAll('#tag-filter input[type=checkbox]:checked'))
                            .map(cb => cb.value);
    const params = new URLSearchParams(window.location.search);
    params.set("tags", checkedTags.join(","));
    params.set("page", 1);
    window.location.href = `/?${params.toString()}`;
}
const wrapper = document.getElementById('filter-wrapper');
const toggleBtn = document.getElementById('toggle-filter-btn');

let expanded = localStorage.getItem('filterExpanded') === 'true';

if (expanded) {
    wrapper.style.maxHeight = wrapper.scrollHeight + 'px';
    toggleBtn.innerText = "🔼 Hide Filters";
} else {
    wrapper.style.maxHeight = '0px';
    toggleBtn.innerText = "🔽 Show Filters";
}

toggleBtn.onclick = () => {
    expanded = !expanded;
    wrapper.style.maxHeight = expanded ? wrapper.scrollHeight + 'px' : '0px';
    toggleBtn.innerText = expanded ? "🔼 Hide Filters" : "🔽 Show Filters";
    localStorage.setItem('filterExpanded', expanded);
};
const pageInput = document.getElementById('page-input');
const goBtn = document.getElementById('go-page-btn');

function goToPage() {
    let page = parseInt(pageInput.value);
    let totalPages = window.totalPages;
    if (isNaN(page) || page < 1) page = 1;
    if (page > totalPages) page = totalPages;
    const params = new URLSearchParams(window.location.search);
    params.set("page", page);
    window.location.href = `/?${params.toString()}`;
}

// 点击按钮跳转
goBtn.onclick = goToPage;

// 输入框回车跳转
pageInput.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
    goToPage();
}
});
function addTagFilter(tag) {
  const params = new URLSearchParams(window.location.search);

  let currentTags = params.get("tags") ? params.get("tags").split(",") : [];

  if (!currentTags.includes(tag)) {
    currentTags.push(tag);
  }

  params.set("tags", currentTags.join(","));
  params.set("page", 1);
  window.location.href = `/?${params.toString()}`;
}
async function getBag(filename) {
try {
    const response = await fetch(`/get_bag/${filename}`);
    const data = await response.json();

    if (!data.exists) {
    Swal.fire({
        icon: 'error',
        title: 'Bag Not Found',
        text: 'The bag file does not exist.'
    });
    return;
    }

    // Bag 存在时，弹出选择框
    const result = await Swal.fire({
    title: 'Bag File Found',
    text: 'Do you want to download it or copy its path?',
    icon: 'question',
    showCancelButton: true,
    confirmButtonText: 'Download',
    cancelButtonText: 'Copy Path'
    });

    if (result.isConfirmed) {
    // 下载
    window.location.href = `/download_bag/${filename}`;
    } else if (result.dismiss === Swal.DismissReason.cancel) {
        // 显示路径输入框
        Swal.fire({
            title: 'Bag Path',
            input: 'text',
            inputValue: data.path,
            inputAttributes: {
                readonly: true
            },
            showCancelButton: false,
        });
    }

    } catch (error) {
        Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to fetch bag info.'
        });
    }
}
